<template>
    <div>
        <div class="list-common-table">
            <t-form ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSubmit">
                <t-row>
                    <t-col :span="10">
                        <t-row :gutter="[24, 24]">
                            <t-col :span="4">
                                <t-form-item label="账号名" name="userName">
                                    <t-input
                                        v-model="formData.userName"
                                        class="form-item-content"
                                        placeholder="请输入账户名"
                                        :style="{ minWidth: '134px' }"
                                    />
                                </t-form-item>
                            </t-col>
                            <t-col :span="4">
                                <t-form-item label="账号状态" name="status">
                                    <t-select
                                        v-model="formData.status"
                                        class="form-item-content"
                                        :options="CONTRACT_STATUS_OPTIONS"
                                        placeholder="请选择账户状态"
                                    />
                                </t-form-item>
                            </t-col>
                            <t-col :span="4">
                                <t-form-item label="用户昵称" name="nickName">
                                    <t-input
                                        v-model="formData.nickName"
                                        class="form-item-content"
                                        type="search"
                                        placeholder="请输入用户昵称"
                                        :style="{ minWidth: '134px' }"
                                    />
                                </t-form-item>
                            </t-col>
                            <t-col :span="4">
                                <t-form-item label="手机号" name="phone">
                                    <t-input
                                        v-model="formData.phone"
                                        class="form-item-content"
                                        type="search"
                                        placeholder="请输入手机号"
                                        :style="{ minWidth: '134px' }"
                                    />
                                </t-form-item>
                            </t-col>
                            <t-col :span="4">
                                <t-form-item label="邮箱" name="email">
                                    <t-input
                                        v-model="formData.email"
                                        class="form-item-content"
                                        type="search"
                                        placeholder="邮箱"
                                        :style="{ minWidth: '134px' }"
                                    />
                                </t-form-item>
                            </t-col>
                        </t-row>
                    </t-col>

                    <t-col :span="2" class="operation-container">
                        <t-button
                            theme="primary"
                            type="submit"
                            :style="{ marginLeft: 'var(--td-comp-margin-s)' }"
                            @click="fetchData"
                        >
                            {{ t('components.commonTable.query') }}
                        </t-button>
                        <t-button type="reset" variant="base" theme="default">
                            {{ t('components.commonTable.reset') }}
                        </t-button>
                    </t-col>

                    <div class="left-operation-container" style="margin-top: 25px">
                        <t-button @click="createUser">创建用户</t-button>
                        <!--                    <t-button variant="base" theme="default"> 导出用户</t-button>-->
                    </div>
                </t-row>
            </t-form>

            <t-row justify="space-between"></t-row>

            <div class="table-container">
                <t-table
                    :data="data"
                    :columns="COLUMNS"
                    :row-key="rowKey"
                    :hover="hover"
                    :pagination="pagination"
                    :loading="dataLoading"
                    :selected-row-keys="selectedRowKeys"
                    :header-affixed-top="headerAffixedTop"
                    row-selectable
                    @page-change="rehandlePageChange"
                    @change="rehandleChange"
                >
                    <template #avatar="{ row }">
                        <div class="tdesign-demo-image-viewer__base">
                            <t-image-viewer :images="[row.avatar]">
                                <template #trigger="{ open }">
                                    <div class="tdesign-demo-image-viewer__ui-image">
                                        <img
                                            :alt="row.id"
                                            :src="row.avatar"
                                            class="tdesign-demo-image-viewer__ui-image--img"
                                        />
                                        <div class="tdesign-demo-image-viewer__ui-image--hover" @click="open">
                                            <span> 预览</span>
                                        </div>
                                    </div>
                                </template>
                            </t-image-viewer>
                        </div>
                    </template>
                    <template #status="{ row }">
                        <t-tag v-if="row.status === 0" theme="success" variant="light">
                            {{ t('components.commonTable.contractStatusEnum.fail') }}
                        </t-tag>
                        <t-tag v-if="row.status === 1" theme="danger" variant="light">
                            {{ t('components.commonTable.contractStatusEnum.audit') }}
                        </t-tag>
                    </template>
                    <template #op="slotProps">
                        <t-space>
                            <t-link theme="primary" @click="handleClickDetail(slotProps)">修改</t-link>
                            <t-link v-if="slotProps.row.status === 0" theme="danger" @click="handleClickFen(slotProps)">
                                封禁
                            </t-link>
                            <t-link
                                v-else-if="slotProps.row.status === 1"
                                theme="primary"
                                @click="handleClickFen(slotProps)"
                            >
                                解封
                            </t-link>
                            <t-link theme="danger" @click="handleClickDelete(slotProps)">删除</t-link>
                        </t-space>
                    </template>
                </t-table>
                <t-dialog
                    v-model:visible="confirmVisible"
                    header="确认删除当前所选用户？"
                    :body="confirmBody"
                    :on-cancel="onCancelDelete"
                    @confirm="onConfirmDelete"
                />
            </div>
        </div>

        <!-- 创建用户弹出框 -->
        <t-dialog
            v-model:visible="createDialogVisible"
            width="55%"
            header="创建新用户"
            placement="center"
            :on-cancel="onCancelCreate"
            @confirm="onConfirmCreate"
        >
            <t-form ref="createForm" :data="newUserFormData" :label-width="80" colon>
                <t-row :gutter="[0, 12]">
                    <t-col :span="5">
                        <t-form-item label="头像" name="avatar">
                            <t-upload
                                ref="uploadRef"
                                action="http://localhost:8081/api/file/upload"
                                :multiple="multiple"
                                :headers="upload.headers"
                                :size-limit="{ size: 10, unit: 'MB' }"
                                :max="1"
                                :allow-upload-duplicate-file="true"
                                :theme="'image'"
                                accept="image/jpeg, image/png"
                                :show-thumbnail="false"
                                :show-image-file-name="false"
                                class="upload_image"
                                @fail="handleFail"
                                @success="handleCreateSuccess"
                                @one-file-success="onOneFileSuccess"
                                @remove="deleteImg"
                            />
                        </t-form-item>
                        <t-form-item label="账号名" name="userName">
                            <t-input v-model="newUserFormData.userName" placeholder="请输入账户名" />
                        </t-form-item>
                        <t-form-item label="用户昵称" name="nickName">
                            <t-input v-model="newUserFormData.nickName" placeholder="请输入用户昵称" />
                        </t-form-item>
                        <t-form-item label="密码" name="password">
                            <t-input v-model="newUserFormData.password" placeholder="请输入用户密码" />
                        </t-form-item>
                    </t-col>
                    <t-col :span="1"></t-col>
                    <t-col :span="5">
                        <t-form-item label="手机号" name="phone">
                            <t-input v-model="newUserFormData.phone" placeholder="请输入手机号" />
                        </t-form-item>
                        <t-form-item label="邮箱" name="email">
                            <t-input v-model="newUserFormData.email" placeholder="请输入邮箱" />
                        </t-form-item>
                        <t-form-item label="账号状态" name="status">
                            <t-select
                                v-model="newUserFormData.status"
                                :options="CONTRACT_STATUS_OPTIONS"
                                placeholder="请选择账户状态"
                            />
                        </t-form-item>
                        <t-form-item label="性别" name="sex">
                            <t-select v-model="newUserFormData.sex" :options="sexs" placeholder="请选择性别" />
                        </t-form-item>
                    </t-col>
                </t-row>
            </t-form>
        </t-dialog>

        <!-- 修改用户弹出框 -->
        <t-dialog
            v-model:visible="updateDialogVisible"
            width="55%"
            header="修改新用户"
            placement="center"
            :on-cancel="onCancelUpdate"
            @confirm="onConfirmUpdate"
        >
            <t-form ref="createForm" :data="updateUserFormData" :label-width="80" colon>
                <t-row :gutter="[0, 16]">
                    <t-col :span="5">
                        <t-form-item label="头像" name="avatar">
                            <div class="avatar-preview">
                                <t-image
                                    :src="updateUserFormData.avatar"
                                    :style="{ width: '110px', height: '110px' }"
                                    style="margin-right: 50px"
                                />
                            </div>
                            <t-upload
                                ref="uploadRef"
                                action="http://localhost:8081/api/file/upload"
                                :multiple="multiple"
                                :headers="upload.headers"
                                :size-limit="{ size: 10, unit: 'MB' }"
                                :max="1"
                                :allow-upload-duplicate-file="true"
                                :theme="'image'"
                                accept="image/jpeg, image/png"
                                :show-thumbnail="false"
                                :show-image-file-name="false"
                                class="upload_image"
                                @fail="handleFail"
                                @success="handleSuccess"
                                @one-file-success="onOneFileSuccess"
                                @remove="deleteImg"
                            />
                        </t-form-item>
                        <t-form-item label="账号名" name="userName">
                            <t-input v-model="updateUserFormData.userName" placeholder="请输入账户名" />
                        </t-form-item>
                        <t-form-item label="用户昵称" name="nickName">
                            <t-input v-model="updateUserFormData.nickName" placeholder="请输入用户昵称" />
                        </t-form-item>
                        <t-form-item label="密码" name="password">
                            <t-input v-model="updateUserFormData.password" placeholder="请输入用户密码" />
                        </t-form-item>
                    </t-col>
                    <t-col :span="1"></t-col>
                    <t-col :span="5">
                        <t-form-item label="手机号" name="phone">
                            <t-input v-model="updateUserFormData.phone" placeholder="请输入手机号" />
                        </t-form-item>
                        <t-form-item label="邮箱" name="email">
                            <t-input v-model="updateUserFormData.email" placeholder="请输入邮箱" />
                        </t-form-item>
                        <t-form-item label="账号状态" name="status">
                            <t-select
                                v-model="updateUserFormData.status"
                                :options="CONTRACT_STATUS_OPTIONS"
                                placeholder="请选择账户状态"
                            />
                        </t-form-item>
                        <t-form-item label="性别" name="sex">
                            <t-select v-model="updateUserFormData.sex" :options="sexs" placeholder="请选择性别" />
                        </t-form-item>
                    </t-col>
                </t-row>
            </t-form>
        </t-dialog>
    </div>
</template>

<script setup lang="ts">
import { MessagePlugin, PageInfo, PrimaryTableCol, TableRowData } from 'tdesign-vue-next';
import { computed, onMounted, reactive, ref } from 'vue';

import { addRegularUser, blockedAndUnseal, deleteUserById, getUserById, getUserList, updateUserById } from '@/api/user';
import { prefix } from '@/config/global';
import { t } from '@/locales';
import { useSettingStore, useUserStore } from '@/store';

const store = useSettingStore();

const CONTRACT_STATUS_OPTIONS = [
    { value: 0, label: '正常' },
    { value: 1, label: '封禁' },
];
const sexs = [
    { value: 0, label: '男' },
    { value: 1, label: '女' },
];
const COLUMNS: PrimaryTableCol[] = [
    {
        title: '头像',
        fixed: 'left',
        ellipsis: true,
        align: 'center', // 可以根据需要调整对齐方式
        colKey: 'avatar',
        width: 120, // 设置合适的宽度
        // cell: (h, { row }) => {
        //     return h('img', {
        //         src: row.avatar,
        //         alt: 'Avatar',
        //         style: {
        //             width: '25px', // 设置图片宽度
        //             height: '25px', // 设置图片高度
        //             objectFit: 'cover', // 图片填充方式
        //             padding: '0px', // 图片周围的间距
        //             margin: '0px', // 图片周围的间距
        //         },
        //     });
        // },
    },
    {
        title: '账户',
        fixed: 'left',
        ellipsis: true,
        align: 'left',
        colKey: 'userName',
    },
    {
        title: '昵称',
        width: 100,
        ellipsis: true,
        colKey: 'nickName',
    },
    {
        title: '状态',
        colKey: 'status',
        width: 100,
    },
    {
        title: '性别',
        width: 100,
        ellipsis: true,
        colKey: 'sex',
        cell: (h, { row }) => {
            return sexs[row.sex].label;
        },
    },
    {
        title: '手机号',
        width: 130,
        ellipsis: true,
        colKey: 'phone',
    },

    {
        title: '最后登录IP',
        width: 130,
        ellipsis: true,
        colKey: 'loginIp',
    },
    {
        title: 'IP地址',
        width: 160,
        ellipsis: true,
        colKey: 'loginIpAttribution',
    },
    {
        title: '邮箱',
        width: 190,
        ellipsis: true,
        colKey: 'email',
    },
    {
        title: '创建者',
        width: 120,
        ellipsis: true,
        colKey: 'createBy',
    },
    {
        title: '创建时间',
        width: 190,
        ellipsis: true,
        colKey: 'createTime',
        cell: (h, { row }) => {
            const isoDateString = row.createTime;
            const date = new Date(isoDateString);
            const formattedDate = date
                .toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false,
                })
                .replace(/\//g, '-');
            return formattedDate;
        },
    },
    {
        align: 'center',
        fixed: 'right',
        width: 160,
        colKey: 'op',
        title: '操作',
    },
];

const searchForm = {
    userName: '',
    nickName: '',
    status: '',
    phone: '',
    email: '',
    pageNum: 1,
    pageSize: 20,
};

const formData = ref({ ...searchForm });

const rowKey = 'index';
const hover = true;

/**
 * 存储表格数据
 */
const data = ref([]);

const dataLoading = ref(false);

// 初始化
onMounted(() => {
    fetchData();
});
/**
 * 搜索
 */
const fetchData = async () => {
    dataLoading.value = true;
    try {
        const response = await getUserList(formData.value);
        console.log('response', response);
        const { records, total } = response;
        console.log('records', records);
        data.value = records;
        pagination.value = {
            ...pagination.value,
            total,
        };
    } catch (e) {
        console.log(e);
    } finally {
        dataLoading.value = false;
    }
};
/**
 * 分页
 * @param pageInfo
 * @param newDataSource
 */
const rehandlePageChange = (pageInfo: PageInfo, newDataSource: TableRowData[]) => {
    console.log('分页查询', pageInfo, newDataSource);
    formData.value.pageNum = pageInfo.current;
    formData.value.pageSize = pageInfo.pageSize;
    fetchData();
};
/**
 * 分页配置
 */
const pagination = ref({
    defaultPageSize: 5,
    total: 10,
    defaultCurrent: 1,
});
// 创建用户
const createUser = () => {
    createDialogVisible.value = true;
};
// 弹出框显示状态
let createDialogVisible = ref(false);

// 新建用户的表单数据
const newUserFormData = ref({
    avatar: '',
    userName: '',
    nickName: '',
    status: 0,
    phone: '',
    email: '',
    sex: 0,
    password: '',
});
// 取消创建用户
const onCancelCreate = () => {
    createDialogVisible.value = false;
    // 清空表单数据
    newUserFormData.value = {
        avatar: '',
        userName: '',
        nickName: '',
        status: 0,
        phone: '',
        email: '',
        sex: 0,
        password: '',
    };
};

// 确认创建用户
const onConfirmCreate = async () => {
    try {
        await addRegularUser(newUserFormData.value);
        // 重新获取数据
        fetchData();
        createDialogVisible.value = false;
        MessagePlugin.success('用户创建成功');
    } catch (error) {
        console.error('创建用户失败:', error);
        MessagePlugin.error('创建用户失败');
    } finally {
        // 清空表单数据
        onCancelCreate();
    }
};

// 修改

const handleClickDetail = (slot: any) => {
    console.log('slot', slot);
    updateUser(slot.row.userId);
};

// 修改用户
const updateUser = async (id: any) => {
    try {
        // 根据id查询修改用户的信息
        const response = await getUserById(id);
        console.log('response', response);
        updateUserFormData.value = response;
        console.log('updateUserFormData', updateUserFormData.value);
        updateDialogVisible.value = true;
    } catch (error) {
        console.error('获取用户信息失败:', error);
        MessagePlugin.error('获取用户信息失败');
    }
};
// 弹出框显示状态修改
const updateDialogVisible = ref(false);

// 修改用户的表单数据
const updateUserFormData = ref({
    id: '',
    avatar: '',
    userName: '',
    nickName: '',
    status: 0,
    phone: '',
    email: '',
    sex: 0,
    password: '',
});
// 取消修改用户
const onCancelUpdate = () => {
    updateDialogVisible.value = false;
    // 清空表单数据
    updateUserFormData.value = {
        id: '',
        avatar: '',
        userName: '',
        nickName: '',
        status: 0,
        phone: '',
        email: '',
        sex: 0,
        password: '',
    };
    // 清空图片上传列表
    resetUpload();
};

// 确认修改用户
const onConfirmUpdate = async () => {
    try {
        await updateUserById(updateUserFormData.value);
        // 重新获取数据
        fetchData();
        createDialogVisible.value = false;
        MessagePlugin.success('用户修改成功');
    } catch (error) {
        console.error('修改用户失败:', error);
        MessagePlugin.error('修改用户失败');
    } finally {
        // 清空表单数据
        onCancelCreate();
        updateDialogVisible.value = false;
        resetUpload();
    }
};

// 删除
const confirmVisible = ref(false);
// 删除用户在表格中的索引
const deleteIdx = ref(-1);
const handleClickDelete = (slot: any) => {
    console.log('slot', slot.rowIndex);
    deleteIdx.value = slot.rowIndex;
    confirmVisible.value = true;
};

const confirmBody = computed(() => {
    if (deleteIdx.value > -1) {
        console.log('data.value', data.value[deleteIdx.value]);
        const { userName } = data.value[deleteIdx.value];
        return `删除后，${userName}的所有用户信息将被清空，且无法恢复`;
    }
    return '';
});

const onConfirmDelete = async () => {
    // 真实业务请发起请求
    // 主义需要加await 等待删除请求完成后在请求查询 不然可能没有删除成功就请求了
    await deleteUserById(data.value[deleteIdx.value].userId);
    // 重新获取数据
    fetchData();
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    // 恢复删除索引
    resetIdx();
};
// 取消删除
const onCancelDelete = () => {
    resetIdx();
};
const resetIdx = () => {
    deleteIdx.value = -1;
};

// 复位
const onReset = (val: unknown) => {
    console.log(val);
};

// 提交
const onSubmit = (val: unknown) => {
    console.log(val);
    console.log(formData.value);
};

const rehandleChange = (changeParams: unknown, triggerAndData: unknown) => {
    console.log('统一Change', changeParams, triggerAndData);
};
const selectedRowKeys = ref([1, 2]);

const headerAffixedTop = computed(
    () =>
        ({
            offsetTop: store.isUseTabsRouter ? 48 : 0,
            container: `.${prefix}-layout`,
        }) as any, // TO BE FIXED
);
// 账户封禁解封
const handleClickFen = async (slot: any) => {
    console.log('slot', slot.rowIndex);
    await blockedAndUnseal(slot.row.userId);
    fetchData();
};
const userStore = useUserStore();
const { token } = userStore;
console.log('token', token);
// 图片上传
const upload = reactive({
    actionUrl: `http://localhost:8081/api/file/upload`,
    headers: {
        Authorization: token,
    },
});

const multiple = ref(false);
const uploadRef = ref(null);

const handleFail = (context: any) => {
    console.log('Upload failed:', context);
};
// 文件上传完成
const handleSuccess = (context: any) => {
    console.log('Upload success Url:', context.response.data);
    updateUserFormData.value.avatar = context.response.data;
};

const onOneFileSuccess = (context: any) => {
    console.log('One file upload success:', context);
};

const deleteImg = (context: any) => {
    console.log('Delete image:', context);
};

const resetUpload = () => {};

// 创建文件上传完成
const handleCreateSuccess = (context: any) => {
    console.log('Create success Url:', context.response.data);
    newUserFormData.value.avatar = context.response.data;
};
</script>

<style lang="less" scoped>
.list-common-table {
    background-color: var(--td-bg-color-container);
    padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
    border-radius: var(--td-radius-medium);

    .table-container {
        margin-top: var(--td-comp-margin-xxl);
    }
}

.form-item-content {
    width: 100%;
}

.operation-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .expand {
        .t-button__text {
            display: flex;
            align-items: center;
        }
    }
}

.payment-col {
    display: flex;

    .trend-container {
        display: flex;
        align-items: center;
        margin-left: var(--td-comp-margin-s);
    }
}

.tdesign-demo-image-viewer__ui-image {
    width: 100%;
    height: 100%;
    display: inline-flex;
    position: relative;
    justify-content: center;
    align-items: center;
    border-radius: var(--td-radius-small);
    overflow: hidden;
}

.tdesign-demo-image-viewer__ui-image--hover {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    background-color: rgba(0, 0, 0, 0.6);
    color: var(--td-text-color-anti);
    line-height: 22px;
    transition: 0.2s;
}

.tdesign-demo-image-viewer__ui-image:hover .tdesign-demo-image-viewer__ui-image--hover {
    opacity: 1;
    cursor: pointer;
}

.tdesign-demo-image-viewer__ui-image--img {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    cursor: pointer;
    position: absolute;
}

.tdesign-demo-image-viewer__ui-image--footer {
    padding: 0 16px;
    height: 56px;
    width: 100%;
    line-height: 56px;
    font-size: 16px;
    position: absolute;
    bottom: 0;
    color: var(--td-text-color-anti);
    background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0) 100%);
    display: flex;
    box-sizing: border-box;
}

.tdesign-demo-image-viewer__ui-image--title {
    flex: 1;
}

.tdesign-demo-popup__reference {
    margin-left: 16px;
}

.tdesign-demo-image-viewer__ui-image--icons .tdesign-demo-icon {
    cursor: pointer;
}

.tdesign-demo-image-viewer__base {
    width: 35px;
    height: 35px;
    margin: 0px auto;
    //border: 4px solid var(--td-bg-color-secondarycontainer);
    border-radius: var(--td-radius-medium);
}

.avatar-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px; /* 调整图片和上传组件之间的间距 */
}

.avatar-preview img {
    width: 100px;
    height: 100px;
    object-fit: cover; /* 确保图片覆盖整个区域 */
}
</style>
